package top.codecrab.eblog.config;

import cn.hutool.core.util.ArrayUtil;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Component
public class MyStringRedisSerializer extends StringRedisSerializer {

    @Override
    public String deserialize(byte[] bytes) {
        if (bytes == null) {
            return null;
        }

        if (!Constants.GLOBAL_REDIS_PREFIX_ENABLE) {
            return new String(bytes, StandardCharsets.UTF_8);
        }

        byte[] prefixBytes = Constants.GLOBAL_REDIS_PREFIX.getBytes(StandardCharsets.UTF_8);
        byte[] key = ArrayUtil.addAll(prefixBytes, bytes);
        return new String(key, StandardCharsets.UTF_8);
    }

    @Override
    public byte[] serialize(String string) {
        if (string == null) {
            return null;
        }

        if (!Constants.GLOBAL_REDIS_PREFIX_ENABLE) {
            return string.getBytes(StandardCharsets.UTF_8);
        }

        return (Constants.GLOBAL_REDIS_PREFIX + string).getBytes(StandardCharsets.UTF_8);
    }
}